<template>
  <div>
    <n-space vertical size="large">
      <n-card title="系统配置" size="small">
        <template #header-extra>
          <n-space>
            <n-button type="primary" @click="initDefaults" :loading="loading">初始化默认配置</n-button>
            <n-button @click="load" :loading="loading">刷新</n-button>
          </n-space>
        </template>
        
        <n-data-table 
          :columns="columns" 
          :data="configs" 
          :loading="loading"
          size="small"
        />
      </n-card>
    </n-space>

    <!-- 编辑配置对话框 -->
    <n-modal v-model:show="editShow" preset="card" title="编辑配置" style="width:600px">
      <n-form :model="editForm" label-placement="left" label-width="120px">
        <n-form-item label="配置键">
          <n-input v-model:value="editForm.configKey" :disabled="editMode === 'edit'" />
        </n-form-item>
        <n-form-item label="配置值">
          <n-input v-model:value="editForm.configValue" />
        </n-form-item>
        <n-form-item label="描述">
          <n-input v-model:value="editForm.description" />
        </n-form-item>
        <n-form-item label="值类型">
          <n-select v-model:value="editForm.valueType" :options="typeOptions" />
        </n-form-item>
      </n-form>
      
      <template #footer>
        <n-space justify="end">
          <n-button @click="editShow = false">取消</n-button>
          <n-button type="primary" @click="saveConfig" :loading="saving">保存</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>
<script setup lang="ts">
import { h, ref, onMounted } from 'vue'
import axios from 'axios'
import { NCard, NSpace, NButton, NDataTable, NModal, NForm, NFormItem, NInput, NSelect, NTag, useMessage } from 'naive-ui'

const message = useMessage()
const loading = ref(false)
const saving = ref(false)
const configs = ref<any[]>([])
const editShow = ref(false)
const editMode = ref<'add' | 'edit'>('add')

const editForm = ref({
  configKey: '',
  configValue: '',
  description: '',
  valueType: 'STRING'
})

const typeOptions = [
  { label: '字符串', value: 'STRING' },
  { label: '整数', value: 'INTEGER' },
  { label: '布尔值', value: 'BOOLEAN' },
  { label: 'JSON', value: 'JSON' }
]

const columns = [
  { title: '配置键', key: 'configKey', width: 200 },
  { title: '配置值', key: 'configValue', width: 150 },
  { title: '描述', key: 'description', ellipsis: { tooltip: true } },
  { 
    title: '类型', 
    key: 'valueType', 
    width: 80,
    render: (row: any) => h(NTag, { size: 'small' }, { default: () => row.valueType })
  },
  { 
    title: '更新时间', 
    key: 'updatedAt', 
    width: 160,
    render: (row: any) => new Date(row.updatedAt).toLocaleString()
  },
  { 
    title: '操作', 
    key: 'actions', 
    width: 120,
    render: (row: any) => h('div', { style: 'display:flex;gap:8px' }, [
      h(NButton, { size: 'small', onClick: () => editConfig(row) }, { default: () => '编辑' }),
      h(NButton, { size: 'small', type: 'error', ghost: true, onClick: () => deleteConfig(row.configKey) }, { default: () => '删除' })
    ])
  }
]

async function load() {
  loading.value = true
  try {
    const { data } = await axios.get('/api/configs')
    configs.value = data
  } catch (e) {
    message.error('加载配置失败')
  } finally {
    loading.value = false
  }
}

async function initDefaults() {
  loading.value = true
  try {
    await axios.post('/api/configs/init-defaults')
    await load()
    message.success('默认配置初始化成功')
  } catch (e) {
    message.error('初始化失败')
  } finally {
    loading.value = false
  }
}

function editConfig(config: any) {
  editMode.value = 'edit'
  editForm.value = {
    configKey: config.configKey,
    configValue: config.configValue,
    description: config.description,
    valueType: config.valueType
  }
  editShow.value = true
}

async function saveConfig() {
  saving.value = true
  try {
    if (editMode.value === 'edit') {
      await axios.put(`/api/configs/${editForm.value.configKey}`, {
        value: editForm.value.configValue,
        description: editForm.value.description,
        valueType: editForm.value.valueType
      })
    } else {
      await axios.post('/api/configs', {
        key: editForm.value.configKey,
        value: editForm.value.configValue,
        description: editForm.value.description,
        valueType: editForm.value.valueType
      })
    }
    
    editShow.value = false
    await load()
    message.success('保存成功')
  } catch (e) {
    message.error('保存失败')
  } finally {
    saving.value = false
  }
}

async function deleteConfig(key: string) {
  try {
    await axios.delete(`/api/configs/${key}`)
    await load()
    message.success('删除成功')
  } catch (e) {
    message.error('删除失败')
  }
}

onMounted(() => {
  load()
})
</script>
